/**
 * Created by macos on 14/11/11.
 */

var bcrypt = require('bcrypt');
var crypto = require('crypto');

module.exports = {

  types:{
    description:function(value) {
      return true;
    }
  },

  attributes: {
    serviceName: {
      type: 'string',
      required: true,
      description: '消息服务的名称'
    },
    userId: {
      type: 'string',
      required: false,
      description: '授权用户的id'
    },
    username: {
      type: 'string',
      required: false,
      description: '授权用户的用户名'
    },
    grantType: {
      type: 'string',
      required: true,
      enum: ['client_credentials','password','refresh_token','code',"implicit"],
      description: '获取令牌的类型'
    },
    tokenType: {
      type: 'string',
      required: true,
      defaultsTo:"bearer",
      description: 'token类型'
    },
    scope: {
      type: 'string',
      required: false
    },
    accessToken: {
      type: 'string',
      required: true,
      description: '访问令牌'
    },
    refreshToken: {
      type: 'string',
      required: false,
      description: '刷新令牌'
    },
    expiresTime: {
      type: 'string',
      required: true
    },

    checkTTL: function() {
      var obj = this.toObject();
      return (obj.expiresTime > new Date().getTime());
    }
  },

  beforeValidate:function(values,next) {
      values.accessToken = crypto.randomBytes(32).toString('hex');
      values.expiresTime = new Date().getTime() + 3600 * 1000+"";
      next();
  },

  beforeCreate: function (values, next) {
      //隐式授权不验证客户端证书
      if(values.grantType==="implicit"){
          return next();
      }

    //根据用户名、密码校验获取令牌
    MessageService.findOne({name:values.serviceName})
      .exec(function(err, result){
        if (err) {
          sails.log.error(err);
          return next(err);
        }

        if (_.has(result, 'id')) {
          if(!values.authorization){
              err = new Error();
              err.message = 'authorization not find!';
              err.status = 404;
              return next(err);
          }
          if(!values.timestamp){
              err = new Error();
              err.message = 'timestamp not find!';
              err.status = 404;
              return next(err);
          }
          var authArray = [];
          authArray.push(values.serviceName);
          authArray.push(result.secret);
          authArray.push(values.timestamp);
          authArray.sort();
          var authorization = authArray[0]+authArray[1]+authArray[2];

          var check = bcrypt.compareSync(authorization, values.authorization);

          if (check) { //校验成功，生成token
              delete values.authorization;
              delete values.timestamp;

              next();
          }  else {
              err = new Error();
              err.message = 'authorization is error';
              err.status = 403;
              return next(err);
          }

        } else {

          err = new Error();
          err.message = '\''+ values.serviceName + '\' is not exist!';
          err.status = 404;

          return next(err);
        }

      });

  },

  beforeUpdate:function (values, next) {

  }
}